package com.aw.baselib.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.aw.baselib.R
import com.aw.baselib.base.AwBaseApplication.Companion.instance
import com.aw.baselib.util.AwDataUtil.isEmpty
import com.aw.baselib.util.AwLog.d
import com.aw.baselib.util.AwToastUtil.showShort
import com.aw.baselib.widgets.AwViewCustomToolbar
import io.reactivex.disposables.CompositeDisposable
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by hzw
 */
abstract class AwBaseFragment : Fragment(), AwBaseView, View.OnClickListener {
    protected var mActivity: AwBaseActivity? = null
    protected var mCompositeSubscription: CompositeDisposable? = null
    protected var TAG = ""
    protected var rootView: View? = null
    protected var mToolbar: AwViewCustomToolbar? = null
    protected var mFragmentManager: FragmentManager? = null
    protected abstract val layoutId: Int
    protected fun initData() {}
    protected fun initView() {}
    protected fun initListener() {}
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshByBus(type: AwBaseEvent?) {
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as AwBaseActivity
        mFragmentManager = mActivity!!.myFragmentManager
        EventBus.getDefault().register(this)
    }

    override fun onDetach() {
        EventBus.getDefault().unregister(this)
        super.onDetach()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        TAG = javaClass.simpleName
        mCompositeSubscription = CompositeDisposable()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        rootView = inflater.inflate(layoutId, container, false)
        initView()
        initData()
        initListener()
        requireView().isClickable = true // 防止点击穿透，底层的fragment响应上层点击触摸事件
        return rootView
    }

    protected fun dismissDialog() {
        if (mActivity == null) {
            return
        }
        mActivity!!.dismissDialog()
    }

    override fun showLoadingDialog() {
        if (mActivity == null) {
            return
        }
        mActivity!!.showLoadingDialog()
    }

    override fun dismissLoadingDialog() {
        if (mActivity == null) {
            return
        }
        mActivity!!.dismissLoadingDialog()
    }

    fun showDialogToFinish(msg: String) {
        if (mActivity == null) {
            showMsg(msg)
            return
        }
        mActivity!!.showDialogToFinish(msg)
    }

    protected fun showDialogToBack(msg: String) {
        if (mActivity == null) {
            showMsg(msg)
            return
        }
        mActivity!!.showDialogToBack(msg)
    }

    fun showDialog(msg: String) {
        if (mActivity == null) {
            showMsg(msg)
            return
        }
        mActivity!!.showDialog(msg)
    }

    fun showDialog(msg: String, listener: View.OnClickListener?) {
        if (mActivity == null) {
            showMsg(msg)
            return
        }
        mActivity!!.showDialog(msg, listener)
    }

    fun showDialogWithCancelDismiss(msg: String, confirmListener: View.OnClickListener?) {
        if (mActivity == null) {
            showMsg(msg)
            return
        }
        mActivity!!.showDialogWithCancelDismiss(msg, confirmListener)
    }

    fun showDialogWithCancelFinish(msg: String, confirmListener: View.OnClickListener?) {
        if (mActivity == null) {
            showMsg(msg)
            return
        }
        mActivity!!.showDialogWithCancelFinish(msg, confirmListener)
    }

    fun showDialogCustomLeftAndRight(
        msg: String?,
        leftTxt: String?,
        rightTxt: String?,
        leftListener: View.OnClickListener?,
        rightListener: View.OnClickListener?
    ) {
        if (mActivity == null) {
            return
        }
        mActivity!!.showDialogCustomLeftAndRight(
            msg,
            leftTxt,
            rightTxt,
            leftListener,
            rightListener
        )
    }

    fun showInputDialog(
        title: String?,
        hintMsg: String?,
        showCancelBtn: Boolean,
        callback: AwViewDialog.InputCallback?
    ) {
        if (mActivity == null) {
            return
        }
        mActivity!!.showInputDialog(title, hintMsg, showCancelBtn, callback)
    }

    fun showCommonCustomDialog(
        msg: String?,
        leftTxt: String?,
        rightTxt: String?,
        showTopImg: Boolean,
        showCancelBtn: Boolean,
        leftListener: View.OnClickListener?,
        rightListener: View.OnClickListener?
    ) {
        if (mActivity == null) {
            return
        }
        mActivity!!.showCommonCustomDialog(
            msg,
            leftTxt,
            rightTxt,
            showTopImg,
            showCancelBtn,
            leftListener,
            rightListener
        )
    }

    fun showCommonCustomDialog(
        title: String?,
        msg: String?,
        leftTxt: String?,
        rightTxt: String?,
        showTopImg: Boolean,
        showCancelBtn: Boolean,
        allowCancelOnTouchOutside: Boolean,
        leftListener: View.OnClickListener?,
        rightListener: View.OnClickListener?
    ) {
        mActivity!!.showCommonCustomDialog(
            title,
            msg,
            leftTxt,
            rightTxt,
            showTopImg,
            showCancelBtn,
            allowCancelOnTouchOutside,
            leftListener,
            rightListener
        )
    }

    //========================APP定制部分===================================
    fun showErrorDialog(msg: String, closeListener: View.OnClickListener?) {
        if (mActivity == null) {
            showMsg(msg)
            return
        }
        mActivity!!.showErrorDialog(msg, closeListener)
    }

    //========================APP定制部分结束================================
    override fun showMsg(msg: String?) {
        if (mActivity == null) {
            showShort(instance, msg)
            return
        }
        mActivity!!.showMsg(msg)
    }

    fun showMsg(msgId: Int) {
        if (mActivity == null) {
            showShort(instance, msgId)
            return
        }
        mActivity!!.showMsg(msgId)
    }

    fun showMsg(msg: String?, defaultMsg: String?) {
        if (mActivity == null) {
            showShort(instance, msg)
            return
        }
        mActivity!!.showMsg(msg, defaultMsg)
    }

    protected fun setText(tv: TextView?, content: String?) {
        if (mActivity == null) {
            if (tv != null) {
                tv.text = content
            }
            return
        }
        mActivity!!.setText(tv, content)
    }

    protected fun showView(v: View?, show: Boolean) {
        if (mActivity == null) {
            if (v != null) {
                v.visibility = if (show) View.VISIBLE else View.GONE
            }
            return
        }
        mActivity!!.showView(v, show)
    }

    protected fun setToolbar(
        title: String?,
        leftClickListener: AwViewCustomToolbar.OnLeftClickListener?
    ) {
        mToolbar = requireView().findViewById<View>(R.id.toolbar_custom) as AwViewCustomToolbar
        if (mToolbar != null) {
            mToolbar!!.hideRightView() //一般很少有页面有右侧, 在需要的时候单独加代码显示, 这里统一隐藏
            mToolbar!!.setLeftImg(R.drawable.icon_back)
            if (leftClickListener == null) {
                mToolbar!!.setOnLeftClickListener(object : AwViewCustomToolbar.OnLeftClickListener {
                    override fun onLeftTextClick() {
                        fragmentToBack()
                    }
                })
            } else {
                mToolbar!!.setOnLeftClickListener(leftClickListener)
            }
            if (!isEmpty(title)) {
                mToolbar!!.setToolbarTitle(title)
            } else {
                mToolbar!!.hideTitleView()
            }
        }
    }

    protected fun showToDevMsg() {
        if (mActivity == null) {
            return
        }
        mActivity!!.showToDevMsg()
    }

    protected fun setToolbarWithBackImg(
        title: String?,
        leftClickListener: AwViewCustomToolbar.OnLeftClickListener?
    ) {
        setToolbar(title, leftClickListener)
        if (mToolbar != null) {
            mToolbar!!.setLeftImg(R.drawable.icon_back)
            mToolbar!!.hideRightView()
        }
    }

    protected fun setToolbarHideLeftAndRight(
        title: String?,
        leftClickListener: AwViewCustomToolbar.OnLeftClickListener?
    ) {
        setToolbar(title, leftClickListener)
        if (mToolbar != null) {
            mToolbar!!.hideLeftView()
            mToolbar!!.hideRightView()
        }
    }

    protected fun setToolbarHideLeftWithRightImg(
        title: String?,
        viewId: Int,
        rightClickListener: AwViewCustomToolbar.OnRightClickListener?
    ) {
        setToolbar(title, null)
        if (mToolbar != null) {
            mToolbar!!.hideLeftView()
            mToolbar!!.showRightView()
            mToolbar!!.setRightImg(viewId)
            mToolbar!!.setOnRightClickListener(rightClickListener)
        }
    }

    /**
     * 跳转activity
     *
     * @param clazz
     * @param params 传值格式  key,value
     */
    fun toClass(clazz: Class<*>?, needFinish: Boolean, vararg params: Any?) {
        if (mActivity == null) {
            return
        }
        mActivity!!.toClass(clazz, needFinish, *params)
    }

    /**
     * 跳转activity(不传参)
     *
     * @param clazz
     */
    fun toClass(clazz: Class<*>?, needFinish: Boolean) {
        if (mActivity == null) {
            return
        }
        mActivity!!.toClass(clazz, needFinish)
    }

    fun toClassForResult(clazz: Class<*>?, requestCode: Int) {
        if (mActivity == null) {
            return
        }
        mActivity!!.toClassForResult(clazz, requestCode)
    }

    /**
     * 跳转fragment
     *
     * @param params 传值格式  key,value
     */
    fun toClass(viewId: Int, fragment: Fragment?, addBackStack: Boolean, vararg params: Any?) {
        if (mActivity == null) {
            return
        }
        mActivity!!.toClass(viewId, fragment!!, addBackStack, *params)
    }

    /**
     * 跳转fragment
     *
     * @param params 传值格式  key,value
     */
    fun toClassChild(viewId: Int, fragment: Fragment, addBackStack: Boolean, vararg params: Any?) {
        val transaction = childFragmentManager.beginTransaction()
        val isTagNull = null == childFragmentManager.findFragmentByTag(fragment.javaClass.name)
        d("toClassChild, fragment: " + fragment.javaClass.name + " ,isAdded: " + fragment.isAdded + " ,findTag is null?: " + isTagNull)
        if (!fragment.isAdded && null == childFragmentManager.findFragmentByTag(fragment.javaClass.name)) {
            childFragmentManager.executePendingTransactions()
            if (params != null) {
                try {
                    fragment.arguments = mActivity!!.getFragmentBundle(*params)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            if (addBackStack) {
                transaction.add(viewId, fragment, fragment.javaClass.name)
                transaction.addToBackStack(fragment.javaClass.name)
            } else {
                transaction.replace(viewId, fragment, fragment.javaClass.name)
            }
            transaction.commitAllowingStateLoss()
        } else {
            d("toClassChild, fragment: " + fragment.javaClass.name + " 已经存在, 直接展示出来")
            transaction.show(fragment).commitAllowingStateLoss()
        }
    }

    /**
     * 跳转fragment(不传参)
     *
     */
    fun toClass(viewId: Int, fragment: Fragment?, addBackStack: Boolean) {
        if (mActivity == null) {
            return
        }
        mActivity!!.toClass(viewId, fragment!!, addBackStack, *arrayOfNulls<Any>(0))
    }

    fun fragmentToBack() {
        if (mActivity == null) {
            return
        }
        mActivity!!.fragmentToBack()
    }

    fun popAllToBack() {
        if (mActivity == null) {
            return
        }
        mActivity!!.popAllToBack()
    }

    override fun onClick(v: View) {}
    override fun onDestroyView() {
        super.onDestroyView()
    }
}